package com.china08.yxyapi.api.comm.upload;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.util.YXCSPUtil;

@CrossOrigin
@RestController
public class UploadFileForSchoolBadgeController extends YxyApiBaseController {

    @Autowired
    YXCSPUtil yxcspUtil;

    @RequestMapping(value = "/api_yw/comm/upload/schoolbadge/image", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel upLoadWenDoc(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        RespModel respModel = new RespModel();
        try {
            Assert.isTrue((file != null), "为选择文件");

            // 验证文件类型
            String filePostfix = FilenameUtils.getExtension(file.getOriginalFilename());
            Assert.isTrue("png,bmp,jpg,gif,jpeg,JPEG,JPG".contains(filePostfix), "文件类型错误,请上传png,bmp,jpg,gif,jpeg,JPEG,JPG类型图片");

            // 获取图片的宽度和高度
            // 转换成double可以计算小数,宽度和高度的差为5个像素
            BufferedImage image = ImageIO.read(file.getInputStream());
            int width = image.getWidth();
            int height = image.getHeight();
            Assert.isTrue(width > 0, "无法获取图片的宽度");
            Assert.isTrue(height > 0, "无法获取图片的高度");
            Assert.isTrue((Math.abs(width - height) >= 0) && (Math.abs(width - height) <= 5), "请上传1:1比例的透明背景的图片(例如:60*60像素的图片)");

            // 上传图片
            String url = yxcspUtil.push(file);
            respModel.url = url;
        } catch (Exception e) {
            respModel.success = false;
            respModel.msg = e.getMessage();
        }
        return respModel;
    }

    public static class RespModel extends YxyApiRespModel {
        public String url;
        public boolean success = true;
        public String msg = "";
    }

}
